package com.demo.optional;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.druid.support.console.Option;
import com.common.interceotpr.AuthInterceptor;
import com.common.interceotpr.ExceptionInterceptor;
import com.common.util.Conditions;
import com.common.util.FormatUtil;
import com.demo.common.model.Optional;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Page;

public class OptionalController extends Controller {
	
	public void index() {
		render("list.html");
	}
	
	@Before({AuthInterceptor.class, ExceptionInterceptor.class})
	public void save() {
		Optional optional = getModel(Optional.class);
		optional.setUserId(AuthInterceptor.getUserId(getRequest()));
		optional.setCreateTime(FormatUtil.formatDate(FormatUtil.getDate(), FormatUtil.pattern_ymd_hms));
		try {
			if(!optional.save()) {
				throw new IllegalArgumentException("保存失败!");
			}
		} catch (ActiveRecordException e) {
			if(e.getCause().toString().indexOf("com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException") != -1) {
				throw new IllegalArgumentException("该信号已经添加自选!");
			}
		};
	}
	
	@Before(AuthInterceptor.class)
	public void paginate() {
		int page = getParaToInt("page");
		int rows = getParaToInt("rows");
		
		Conditions condio = new Conditions();
		
		condio.setValueQuery(Conditions.EQUAL, "userId", AuthInterceptor.getUserId(getRequest()));
		
		Page<Optional> paginate = Optional.dao.paginate(page, rows, condio);
		Map result = new HashMap();
		result.put("total", paginate.getTotalRow());
		result.put("rows", paginate.getList());
		renderJson(result);
	}
	
	@Before({AuthInterceptor.class, ExceptionInterceptor.class})
	public void remove() {
		if(!Optional.dao.deleteById(getParaToInt("id")))
			throw new IllegalArgumentException("删除失败!");;
	}
}
